package com.sgb.kjwl.view.ui.fragment.self;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentGoodsStateBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.user.GoodsStateEntity;
import com.sgb.kjwl.view.ui.MoneyTextWatcher;
import com.sgb.kjwl.view.ui.adapter.self.publish.GoodsStateAdapter;
import com.sgb.kjwl.view.widget.EditPopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.self.publish.GoodsListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.List;

import javax.inject.Inject;

/**
 * Description:
 * Author zhengkewen
 */
public class GoodsStateFragment extends AppFragment {
    public static final String TAG = "";
    public static final String KEY_TYPE = "type";

    private FragmentGoodsStateBinding binding;
    @Inject
    GoodsListModel viewModel;

    private String type = "";
    private boolean isCreate = false;
    private GoodsStateAdapter goodsStateAdapter;
    private EditPopWindow editPopWindow;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreate = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            //     viewModel.getReceptionListViewModel(keyword, type);
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    public static GoodsStateFragment newInstance(String type) {
        GoodsStateFragment fragment = new GoodsStateFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void addSuccessRefreshList() {
        initData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_goods_state, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        type = (String) getArguments().get(KEY_TYPE);
        initView();
        initData();
    }

    private void initView() {
        if (goodsStateAdapter == null) {
            goodsStateAdapter = new GoodsStateAdapter(getActivity(), null, type);
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.rlvView.setLayoutManager(layoutManager);
        binding.rlvView.setAdapter(goodsStateAdapter);
        binding.rlvView.setLoadingMoreEnabled(true);
        binding.rlvView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initData();
            }

            @Override
            public void onLoadMore() {
                if (type.equals("UP")) {
                    viewModel.getGoodsList("1", true);
                } else if (type.equals("DOWN")) {
                    viewModel.getGoodsList("2", true);
                }
            }
        });

        goodsStateAdapter.setonEditClick(new GoodsStateAdapter.onEditClickListener() {
            @Override
            public void onCancelClick(String id, int position) {
                showDeleteDialog(id, position, "cancel");
            }

            @Override
            public void onUpClick(String id, int position) {
                if (type.equals("UP")) {
                    showDeleteDialog(id, position, "up");
                } else if (type.equals("DOWN")) {
                    showDeleteDialog(id, position, "down");
                }
            }

            @Override
            public void onEditeClick(GoodsStateEntity entity, int position) {
//                Intent intent = new Intent(getActivity(), AddGoodsActivity.class);
//                intent.putExtra("id",id);
//                getActivity().startActivity(intent);

                EditText editText = new EditText(getActivity());
                editText.setInputType(8194);
                editText.addTextChangedListener(new MoneyTextWatcher(editText) {
                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });
                editText.setHint("请输入新单价");

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                AlertDialog alertDialog = builder.setMessage("原单价（元）：" + entity.getPrice() + "\n\n新单价（元）：").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        viewModel.modifyPrice(entity.getId(), editText.getText().toString(), type);
                    }
                }).create();
                alertDialog.setView(editText, ResolutionUtil.dp2px(getActivity(), 20), ResolutionUtil.dp2px(getActivity(), 10), ResolutionUtil.dp2px(getActivity(), 20), 0);
                alertDialog.show();

            }
        });

        goodsStateAdapter.setOnItemClick(new AdapterOnItemClick<GoodsStateEntity>() {
            @Override
            public void onItemClick(GoodsStateEntity goodsStateEntity, int position) {

            }
        });

        editPopWindow = new EditPopWindow(getActivity());
        editPopWindow.setBgView(binding.grayLayout);
        editPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
            }
        });
    }

    public void initData() {
        if (type.equals("UP")) {
            viewModel.getGoodsList("1", false);
        } else if (type.equals("DOWN")) {
            viewModel.getGoodsList("2", false);
        }
    }

    public void showGoodsList(List<GoodsStateEntity> datas, boolean isLoadMore) {
        if (isLoadMore) {
            goodsStateAdapter.addDatas(datas);
            binding.rlvView.loadMoreComplete();
            if (goodsStateAdapter.getItemCount() >= viewModel.total) {
                binding.rlvView.setLoadingMoreEnabled(false);
            }
        } else {
            goodsStateAdapter.setDatas(datas);
            binding.rlvView.refreshComplete();
            if (datas.size() == 0) {
                binding.ivEmpty.setVisibility(View.VISIBLE);
            } else {
                binding.ivEmpty.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
           /* case R.id.edit_price_tv:
                editPopWindow.showDownPopwindow(binding.editPriceTv,true);
                break;*/
        }
    }

    private void showDeleteDialog(final String id, int position, String type) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        if (type.equals("up")) {
            tv_message.setText("确定要下架商品吗？");
        } else if (type.equals("down")) {
            tv_message.setText("确定要上架商品吗？");
        } else if (type.equals("cancel")) {
            tv_message.setText("确定要删除商品吗？");
        }

        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type.equals("up")) {
                    viewModel.downGoods(id, position);
                } else if (type.equals("down")) {
                    viewModel.upGoods(id, position);
                } else if (type.equals("cancel")) {
                    viewModel.deleteGoods(id, position);
                }
                roundCornerDialog.dismiss();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    public void refreshList(int position) {
        goodsStateAdapter.getDatas().remove(position - 1);
        goodsStateAdapter.notifyDataSetChanged();
        if (goodsStateAdapter.getDatas().size() == 0) {
            binding.ivEmpty.setVisibility(View.VISIBLE);
        } else {
            binding.ivEmpty.setVisibility(View.GONE);
        }
    }
}
